//
//  HTTPRequestManager.m
//  TestNetWorking
//
//  Created by 蓝泰致铭 on 15/1/30.
//  Copyright (c) 2015年 蓝泰致铭. All rights reserved.
//

#import "HTTPRequestManager.h"
#import "SessionMgr.h"
#import "Utils.h"
#import "AppDelegate.h"
#import "LogoViewController.h"
#import "EncryptStr.h"

#import "HeConstants.h"
#import "HePreferrence.h"
#import "SessionMgr.h"
#import "NSDictionary+getValues.h"

#import "AFSecurityPolicy.h"

@implementation HTTPRequestManager

// 单例
+(HTTPRequestManager *)shareInstance
{
    static HTTPRequestManager * shareInstances = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstances = [[HTTPRequestManager alloc] init];
    });
    
    return shareInstances;
}


/*
 使用声明: 1.如果请求返回数据中带"data"字段，则使用"requestCommonDataByPostMethodWithURL"方法,返回"data"字段的数据
 2.如果请求返回数据中没有带"data"字段，则使用"requestNoneDataByPostMethodWithURL"方法,返回相应的请求数据
 3.如果请求返回的数据与上述两个方法中返回数据都不同，或者返回数据有特殊用途，为了避免冲突，请
 自行添加自用方法,并写明注示，以免别人调用
 
 参数url: 数据接口
 参数value: 请求体 （以键值对的方式，json格式上传）
 参数tag: 该接口的标签值
 回调success: 请求数据成功后回调
 回调failed: 请求数据失败后回调
 */


//get请求
-(void)getRequestMethodWithURL:(NSString * )url withParameters:(NSMutableDictionary*)parameters andBtn:(UIButton*)btn whenSuccess:(HttpRequestSuccess)success Faild:(HttpRequestFailed)failed
{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [AFHTTPRequestOperationManager manager];//只初始化一次
        
    });
    btn.enabled = NO;
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];//返回数据以json格式接收
    
    NSString * strURL = [NSString stringWithFormat:@"%@",url];
    
    
    [_manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        btn.enabled = YES;
        NSDictionary * dic = responseObject;
        
        
        success(self,dic);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        btn.enabled = YES;
        failed(self, error);
        
    }];

}

-(void)closeAlert
{
    [_alert dismissWithClickedButtonIndex:0 animated:YES];
    _alert = nil;
}

//post请求
-(void)postRequestMethodWithURL:(NSString * )url withParameters:(NSMutableDictionary*)parameters andBtn:(UIButton*)btn whenSuccess:(HttpRequestSuccess)success Faild:(HttpRequestFailed)failed
{
    if(![Utils hasNetwork])
    {
//        if(_alert == nil)
//        {
//        _alert = [[UIAlertView alloc]initWithTitle:nil message:@"没有网络" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
//        [_alert show];
//        [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
//        }
        //return;
        
//        [self addLostWlan];
        failed(self,nil);
        return;
    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [AFHTTPRequestOperationManager manager];//只初始化一次
        
    });
    //NSLog(@"5555555");
    btn.enabled = NO;
    //设置返回的数据是JSON格式
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];//返回数据以json格式接收
    
    //设置请求的数据是JSON格式
    _manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //[_manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"application/json"];
    
    // 设置超时时间
    [_manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    _manager.requestSerializer.timeoutInterval = 30.f;
    [_manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    //设置请求上传数据
    [self addPostHeader:parameters];
    
    NSString * strURL = [NSString stringWithFormat:BaseURL, url];
    
    [_manager POST:strURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        btn.enabled = YES;
        NSDictionary * dic = responseObject;
        NSString * strRspCd = [dic objectForKeySDPlan:@"rspCd"];
        NSString * strRspInf = [dic objectForKeySDPlan:@"rspInf"];
        if([strRspCd isEqualToString:@"U0013"])
        {
//            //退出成功
//            [SessionMgr Instance].strUserTokenId = @"";
//            [SessionMgr Instance].isLogined = NO;
//            UserMsgInfo * info = [[UserMsgInfo alloc]init];
//            [SessionMgr Instance].userMsgInfo = info;
//            MyAccountInfo * infos = [[MyAccountInfo alloc]init];
//            [SessionMgr Instance].myAccountInfo = infos;
//            [SessionMgr Instance].isGesturePassword = NO;
//            //清除termid
//            [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"termId"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            
//            [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFY_LOGOUT_SUCCESS object:nil];
            
        }else if ([strRspCd isEqualToString:RspCDSucess])
        {
            success(self,dic);
        }else
        {

            if(_alert == nil)
            {
                _alert = [[UIAlertView alloc]initWithTitle:nil message:strRspInf delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [_alert show];
                [self performSelector:@selector(closeAlert) withObject:nil afterDelay:0.2];
            }

        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//        [self addLostWlan];
        btn.enabled = YES;
        failed(self, error);
        NSLog(@"operation: %@", operation.responseString);
    }];
}



//post请求,带判断rspcd的请求
-(void)postRequestMethodWithURL:(NSString * )url withParameters:(NSMutableDictionary*)parameters andBtn:(UIButton*)btn whenSuccess:(HttpRequestSuccess)success RspCDFailed:(HttpRequestFailedWithRspCD)rspcdFailed Faild:(HttpRequestFailed)failed
{
    
    if(![Utils hasNetwork])
    {
        //        if(_alert == nil)
        //        {
        //        _alert = [[UIAlertView alloc]initWithTitle:nil message:@"没有网络" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
        //        [_alert show];
        //        [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
        //        }
        //return;
        
        //[self addLostWlan];
        failed(self,nil);
        return;
    }
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [AFHTTPRequestOperationManager manager];//只初始化一次
//        [_manager setSecurityPolicy:[HTTPRequestManager setupSecurityPolicy]];
        
    });

    btn.enabled = NO;
    
    //1. 设置安全策略
    [_manager setSecurityPolicy:[HTTPRequestManager setupSecurityPolicy]];
    
    //设置返回的数据是JSON格式
    _manager.responseSerializer = [AFJSONResponseSerializer serializer];//返回数据以json格式接收
    
    
    //设置请求的数据是JSON格式
    _manager.requestSerializer=[AFJSONRequestSerializer serializer];
    
    //[_manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"application/json"];
    
    //_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    //_manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    
    // 设置超时时间
    [_manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    _manager.requestSerializer.timeoutInterval = 10.f;
    [_manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    
    //设置请求上传数据
    [self addPostHeader:parameters];
    
    //把字典转换成字符串
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"jsonStr = %@",jsonStr);
    
    NSString *md5Str = [self toGenerateTheSignature:parameters];
    NSLog(@"签名: %@", md5Str);
    // 将签名加在请求报文末尾
    jsonStr = [jsonStr stringByAppendingString:md5Str];
    
    // 测试加密组件
    EncryptStr* encrypt = [EncryptStr getInstance];
    NSString* encstr = [encrypt startEncrypt:jsonStr key:XXTEA_PROTOCOL_KEY];
    NSLog(@"加密后报文: %@", encstr);

    //NSString * strutf = [encstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
//    jsonData = [encstr dataUsingEncoding:NSUTF8StringEncoding];
//    NSMutableData *myMutablePostData = [NSMutableData dataWithData:jsonData];
    
    //NSString * jsonString = [self JSONString:encstr];
    
    
    NSMutableDictionary * dics = [[NSMutableDictionary alloc]initWithCapacity:10];
    [dics setValue:encstr forKey:@"reqData"];
    
    NSString * strURL = [NSString stringWithFormat:BaseURL,url];
    
    [_manager POST:strURL parameters:dics success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        btn.enabled = YES;
        //解密
        NSDictionary * dics = responseObject;
        
        NSString * stringValue = [dics objectForKeySDPlan:@"rspData"];
        
        NSString * strResponse = @"";
        //测试加密组件
        EncryptStr* encrypt = [EncryptStr getInstance];
        NSString* Deencryptstr = [encrypt startDeencrypt:stringValue key:XXTEA_PROTOCOL_KEY];
        NSLog(@"解密后报文: %@",Deencryptstr);
        if (Deencryptstr.length) {
            strResponse = Deencryptstr;
        }
        NSData * dataResponse = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:dataResponse options:NSJSONReadingMutableLeaves error:nil];
        
        //不解密
        //NSDictionary * dic = responseObject;

        NSString * strRspCd = [dic objectForKeySDPlan:@"rspCd"];
        NSString * strRspInf = [dic objectForKeySDPlan:@"rspInf"];
        if ([strRspCd isEqualToString:RspCDSucess])
        {
            success(self,dic);
        }else
        {
            rspcdFailed(self,dic);
            UIViewController * navC = [self appRootViewController];
            if ([navC isKindOfClass:[UINavigationController class]]) {
                UIViewController *vc1 = [(UINavigationController *)navC visibleViewController];
                //判断如果当前的活动VC是手势界面则不继续推出
                if([vc1 isKindOfClass:[LogoViewController class]])
                {
                    
                }else
                {
                    if(_alert == nil)
                    {
                        _alert = [[UIAlertView alloc]initWithTitle:nil message:strRspInf delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                        [_alert show];
                        [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
                    }
                }
            }else if([navC isKindOfClass:[UITabBarController class]])
            {
                if(_alert == nil)
                {
                    if(_alert == nil)
                    {
                        _alert = [[UIAlertView alloc]initWithTitle:nil message:strRspInf delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                        [_alert show];
                        [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
                    }

                }
            }


        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //获得当前活动的viewcontroller,当前时logocontroller，则禁用alert
            UIViewController * navC = [self appRootViewController];
            NSLog(@"navC = %@",[navC class]);
            if ([navC isKindOfClass:[UINavigationController class]]) {
            UIViewController *vc1 = [(UINavigationController *)navC visibleViewController];
            NSLog(@"vc1 = %@",[LogoViewController class]);
            //判断如果当前的活动VC是手势界面则不继续推出
            if([vc1 isKindOfClass:[LogoViewController class]])
            {
                
            }else
            {
                NSLog(@"666666666");
                if(_alert == nil)
                {
                    _alert = [[UIAlertView alloc]initWithTitle:nil message:@"网络连接超时" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [_alert show];
                    [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
                }
            }
            }else if([navC isKindOfClass:[UITabBarController class]])
            {
                if(_alert == nil)
                {
                    _alert = [[UIAlertView alloc]initWithTitle:nil message:@"网络连接超时" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                    [_alert show];
                    [self performSelector:@selector(closeAlert) withObject:nil afterDelay:2];
                }
            }
        
        //[self addLostWlan];
        btn.enabled = YES;
        failed(self, error);
        NSLog(@"operation: %@", operation.responseString);
    }];
}

- (UIViewController *)appRootViewController
{
    UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *topVC = appRootVC;
    while (topVC.presentedViewController) {
        topVC = topVC.presentedViewController;
    }
    return topVC;
}



#pragma mark - ******** ssl证书检测设置

+ (AFSecurityPolicy*)setupSecurityPolicy
{
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"cmpay"ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
//    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    [securityPolicy setPinnedCertificates:@[certData]];
    securityPolicy.allowInvalidCertificates =NO;//定义了客户端是否信任非法证书
    securityPolicy.validatesDomainName =YES;//是指是否校验在证书中的domain这一个字段
    securityPolicy.validatesCertificateChain =NO;//指的是是否校验其证书链。
    return securityPolicy;
}


//添加post头部信息,请求报文头必须包含：版本号、客户端类型、客户端终端ID、推送ID、请求时间；
-(void)addPostHeader:(NSMutableDictionary*)jsonDict{
    //NSLog(@"strUUID = %@",[[SessionMgr Instance]GetValue:@"termId"]);
    //    NSString *strUUID = @"";
    //    if ([SessionMgr Instance].strUUID.length>0) {
    //        strUUID = [SessionMgr Instance].strUUID;
    //    }
    //
    NSString* strtermid = [HePreferrence getValue:@"termId"];
    if(strtermid == nil || strtermid == NULL || [strtermid isKindOfClass:[NSNull class]])
    {
        
    }else
    {
        [jsonDict setObject:strtermid forKey:@"termId"];
    }
    
    //NSString *strRegistrationID =  [Utils isBlankString:[APService  registrationID]];
    
    NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
    NSString *strVer = [NSString stringWithFormat:@"%@",[dict objectForKey:@"CFBundleShortVersionString"]];
    
    NSString *strSysVersion = [[UIDevice currentDevice] systemVersion]; // "2.2.1"
    
    [jsonDict setObject:strVer forKey:@"appVersion"];    //应用程序版本号
    [jsonDict setObject:strSysVersion forKey:@"osVersion"];  //手机系统版本号
    [jsonDict setObject:@"IOS" forKey:@"termTyp"];
    [jsonDict setObject:CHANNEL_ID forKey:@"channelId"];
    //[jsonDict setObject:strRegistrationID forKey:@"deviceId"];
    [jsonDict setObject:[Utils getFormatCurrDate] forKey:@"requestTm"];
//    [jsonDict setObject:[Utils isBlankString:[SessionMgr Instance].strUserTokenId] forKey:@"tokenId"];
    
//    [jsonDict setValue:[Utils isBlankString:[SessionMgr Instance].userMsgInfo.strUserId] forKey:@"usrNo"];
    
        [jsonDict setObject:@"11111" forKey:@"clientId"];
    //    [jsonDict setObject:[SessionMgr Instance].strClientId forKey:@"clientId"];
    
}

//取消所有请求
-(void)cancelAllRequest
{
    [_manager.operationQueue cancelAllOperations];

}

- (NSString *)toGenerateTheSignature:(NSDictionary *)dictionary {
    NSArray *keyArray = [dictionary allKeys];
    //对参数名进行排序
    keyArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    //拼接有序的参数名-值
    NSMutableString *keyStr = [[NSMutableString alloc] init];
    for (NSString *key in keyArray) {
        [keyStr appendString:key];
        [keyStr appendString:[dictionary objectForKey:key]];
    }
    return [Utils SHA1:keyStr]; //SHA1 加密
}

-(NSString*)GetResponse:(NSData*)dataResponse{
    NSString * strResponse = [[NSString alloc] initWithData:dataResponse encoding:NSUTF8StringEncoding];
    return strResponse;
}

-(NSString *)JSONString:(NSString *)aString {
    NSMutableString *s = [NSMutableString stringWithString:aString];
    [s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    return [NSString stringWithString:s];
}


@end
